from rest_framework import serializers

from utils.base import Util


class Fmt:
    """serializer 格式化"""
    datetime_fmt = '%Y-%m-%d %H:%M:%S'
    # 创建时间和更新时间
    created_at = 'created_at'
    updated_at = 'updated_at'

    @classmethod
    def to_representation(cls, ret: dict, fields: [list, tuple]) -> dict:
        """fmt datetime -> datetime_fmt"""
        datetime_fields = [cls.created_at, cls.updated_at]
        if fields is not None:
            datetime_fields.extend(fields)

        for field in datetime_fields:
            if ret.get(field) is not None:
                ret[field] = Util.datetime_fmt(ret[field], fmt=cls.datetime_fmt)

        return ret


class Serializer(serializers.Serializer):
    """格式化 datetime"""
    datetime_fields = None

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        return Fmt.to_representation(ret, self.datetime_fields)


class ModelSerializer(serializers.ModelSerializer):
    """格式化 datetime"""
    datetime_fields = None

    def to_representation(self, instance):
        ret = super().to_representation(instance)
        return Fmt.to_representation(ret, self.datetime_fields)
